<?

Yii::app()->clientScript->registerCoreScript('jquery.ui');

$D = new CDateFormatter('ru');

?>

<?$this->renderPartial('_list_add_task', array(
    'NEWTASK' => $NEWTASK
))?>

<?
/*
<style type="text/css">
ul#tasklist{ list-style: none; padding: 0; }
ul#tasklist  li.task{
    border: 1px solid #ccc;
    padding: 10px; margin: 0 0 10px 0;
}
ul#tasklist  li.task:hover{
    cursor: pointer;
    background: #f6f6f6;
}
ul#tasklist  li.task.selected{
    background: #f6f6f6;
}
ul#tasklist  li.task.testing{
    opacity: 0.4;
}
ul#tasklist  li.task.critical{
    background: #FEE;
}

div.commentlist{  }
div.commentlist  div.comment{
    padding: 5px; margin: 5px;
    border: 1px solid #eee;
}

div.timer{ font-size: 18px; }

input.button{
    outline: none;
}
input.buttonplay{
    background: url(/images/icons/media_controls_pause_small.png) no-repeat center center;
}

input.buttonpause{
    background: url(/images/icons/media_controls_play_small.png) no-repeat center center;
}

</style>
//*/
?>

<br />
<h3><img src="/images/icons/list.png" class="icon" /> Список задач</h3>

<?$this->renderPartial('_list_filter', array(
    'TASKFILTER' => $TASKFILTER
))?>

<ul id="tasklist">
<?
$js_sorts = $js_inprogress = array();
foreach($TASKS_PROVIDER->getData() as $TASK){
    
    array_push($js_sorts, $TASK->sort);
    
    $inTesting = $TASK->status == $TASK->rstatuses[TaskModule::t('fields', 'Ожидает проверки')];
    $inProgress = array_key_exists($TASK->id, $TASKS_INPROGRESS);
    
    if($inProgress){
        $js_inprogress[$TASK->id] = time() - $TASKS_INPROGRESS[$TASK->id]->time_start - $TASKS_INPROGRESS[$TASK->id]->time_break;
    }
    
    $classes = array('task');
    if($TASK->critical) $classes[] = 'critical';
    if($inTesting and !TaskUser::isManager()) $classes[] = 'testing';
    
    $AUTHOR = $TASK->getRelated('author');
    $FILES = $TASK->getRelated('files');
    
    $responsible = array();
    $RESPUSERS = $TASK->getRelated('responsible');
    foreach($RESPUSERS as $RU){
        $U = $RU->getRelated('user');
        $responsible[$U->id] = $U->GetLink();
    }
    
    ?>
<li class="<?=implode(' ', $classes)?>" id="task<?=$TASK->id?>" onclick="selectTask(<?=$TASK->id?>);">
    
    <input type="hidden" name="id" value="<?=$TASK->id?>" />
    <input type="hidden" name="sort" value="<?=$TASK->sort?>" />
    
    <ul class="col-meta">
     <li class="ID"><?=$TASK->critical?'Критическая задача':'Задача'?> #<?=$TASK->id?></li>
     <li class="date"><?=$D->formatDateTime($TASK->time_create, 'full', 'short')?></li>
     <li class="author">Поставил задачу: <?=$AUTHOR->GetLink()?></li>
     <li class="responsible">
        Ответственные:
        <span id="responsibletask<?=$TASK->id?>"><?=implode(', ',$responsible)?></span>
     </li>
     <li class="responsibleadd">
        <?$formurl=$this->createUrl('tools/addtaskresponsible', array('taskID'=>$TASK->id));?>
        <form action="<?=$formurl?>" method="post">
        <?$this->widget('zii.widgets.jui.CJuiAutoComplete', array(
            'name'=>'responsible',
            'sourceUrl'=>$this->createUrl('tools/ajaxsearchmember', array()),
            'options'=>array( 'minLength'=>2 ),
            'htmlOptions' => array(
                'id' => 'responsible-'.$TASK->id
            )
        ));?>
        <?=CHtml::ajaxSubmitButton(TaskModule::t('app', 'Добавить ответственного'), $formurl, array(
            'update' => '#responsibletask'.$TASK->id
        ))?>
        </form>
     </li>
    </ul>
    <ul class="col-text">
        <li class="text"><?=$TASK->text?></li>
        <?if(!empty($FILES)){?>
        <li class="files_field"><b>Прикреплённые файлы:</b></li>
        <li class="files"><ol class="list">
            <?foreach($FILES as $_F){
                $F = $_F->getRelated('file');
                ?>
                <li class="file"><a href="<?=$F->path.'/'.$F->code?>" target="_blank"><?=$F->name?></a></li>
            <?}?>
        </ol></li>
        <?}?>
    </ul>
    <ul class="col-actions hide">
        <li class="status">
            <? $statusurl = $this->createUrl('tools/savetaskstatus', array('taskID'=>$TASK->id,'backurl'=>$_SERVER['REQUEST_URI'])); ?>
            <form action="<?=$statusurl?>" method="post">
            Статус: <?=Task::model()->statuses[$TASK->status]?>
            </form>
        </li>
        <li class="work <?=$inProgress?'hide':''?>">
            <?=CHtml::button(TaskModule::t('app', 'Приступить к задаче'),array('onclick'=>'Task.start('.$TASK->id.');'))?>
        </li>
        <li class="work-in-process <?=$inProgress?'':'hide'?>">
            <div id="task<?=$TASK->id?>time" class="timer"></div>
            <?=CHtml::button(TaskModule::t('app', 'Приостановить'),array(
                'onclick'=>'Task.pause('.$TASK->id.');',
                'id'=>'task'.$TASK->id.'pausebutton',
                'class'=>'button buttonplay'
            ))?>
            <?=CHtml::button(TaskModule::t('app', 'Остановить выполнение'),array('onclick'=>'Task.stop('.$TASK->id.');'))?><Br />
            Что делал?<br />
            <textarea class="bigtext" onblur="Task.savecomment(<?=$TASK->id?>, this);"><?=$TASKS_INPROGRESS[$TASK->id]->comment?></textarea>
        </li>
        <li class="actions">
            <?
            if(array_key_exists(Yii::app()->user->id, $responsible) and !$inTesting){
                echo CHtml::button(TaskModule::t('app', 'Завершить'),array('onclick'=>'Task.testing('.$TASK->id.');'));
            }
            if(TaskUser::isManager()){
                echo CHtml::button(TaskModule::t('app', 'Отложить'),array('onclick'=>'Task.away('.$TASK->id.');'));
                echo CHtml::button(TaskModule::t('app', 'Отменить'),array('onclick'=>'Task.cancle('.$TASK->id.');'));
                echo CHtml::button(TaskModule::t('app', 'Архивировать'),array('onclick'=>'Task.archive('.$TASK->id.');'));
            }
            ?>
        </li>
    </ul>
    <br />
    <div id="comments-wrapper-<?=$TASK->id?>" class="comments-wrapper">
    <?$this->renderPartial('_list_comment', array(
        'TASK' => $TASK,
        'display' => 'none'
    ))?>
    </div>
    
    <?if(TaskUser::isManager()){?>
        <?$this->renderPartial('_list_timehistory', array(
            'TASK' => $TASK
        ))?>
    <?}?>
    
    <?
    if($inProgress)
        echo CHtml::script('$(function(){ selectTask('.$TASK->id.'); Task.check('.$TASK->id.'); })');
    ?>
</li>
<?}?>
</ul>

<script type="text/javascript">

var TaskHelper = function(){
    
    var self = this;
    
    self._timers = {};
    self._times = {};
    
    <?
    foreach($js_inprogress as $id=>$t){
        echo 'self._times['.$id.'] = '.$t.';';
    }
    ?>
    
    self.sendRequest = function(op, taskID, callback){
        $.getJSON('<?=$this->createUrl('tools/taskaction')?>', {
            'op': op,
            'taskID': taskID
        }, callback);
    };
    
    self.start = function(taskID){
        self.sendRequest('start', taskID, function(data){
            $('#task'+taskID+' ul.col-actions li.work').hide();
            $('#task'+taskID+' ul.col-actions li.work-in-process').show();
            $().toastmessage('showSuccessToast', data.message);
            self._times[taskID] = 0;
            self.check(taskID);
        });
    };
    
    self.stop = function(taskID){
        self.sendRequest('stop', taskID, function(data, textStatus, jqXHR){
            $('#task'+taskID+' ul.col-actions li.work').show();
            $('#task'+taskID+' ul.col-actions li.work-in-process').hide();
            $().toastmessage('showSuccessToast', data.message);
            self._times[taskID] = 0;
            clearTimeout(self._timers[taskID]);
        });
    };
    
    self.pause = function(taskID){
        self.sendRequest('pause_start', taskID, function(data){
            $().toastmessage('showSuccessToast', data.message);
            $('#task'+taskID+'pausebutton')
                .attr('onclick', 'Task.pauseEnd('+taskID+');')
                .removeClass('buttonplay').addClass('buttonpause')
                .val('Возобновить');
            clearTimeout(self._timers[taskID]);
        });
    };
    
    self.pauseEnd = function(taskID){
        self.sendRequest('pause_stop', taskID, function(data){
            $().toastmessage('showSuccessToast', data.message);
            $('#task'+taskID+'pausebutton')
                .attr('onclick', 'Task.pause('+taskID+');')
                .removeClass('buttonpause').addClass('buttonplay')
                .val('Приостановить');
            Task.check(taskID);
        });
    };
    
    self.check = function(taskID){
        $('#task'+taskID+'time').text(
            sprintf('%02d:%02d:%02d', self._times[taskID]/3600, (self._times[taskID] % 3600)/60, (self._times[taskID] % 3600) % 60)
        );
        self._timers[taskID] = setTimeout(function(){ Task.check(taskID); }, 1000);
        self._times[taskID] = self._times[taskID]+1;
    };
    
    self.savecomment = function(taskID, input){
        $.post('<?=$this->createUrl('tools/taskaction', array('op'=>'savecomment'))?>', {
            'taskID': taskID,
            'comment': input.value
        }, function(data){
            data = $.parseJSON(data);
            $().toastmessage('showSuccessToast', data.message);
        });
    };
    
    self.testing = function(taskID){
        self.sendRequest('testing', taskID, function(data){
            $().toastmessage('showSuccessToast', data.message);
        });
    };
    
    self.away = function(taskID){
        self.sendRequest('away', taskID, function(data){
            $().toastmessage('showSuccessToast', data.message);
        });
    };
    
    self.cancle = function(taskID){
        self.sendRequest('cancle', taskID, function(data){
            $().toastmessage('showSuccessToast', data.message);
        });
    };
    
    self.archive = function(taskID){
        self.sendRequest('archive', taskID, function(data){
            $().toastmessage('showSuccessToast', data.message);
        });
    };
    
    
}
var Task = new TaskHelper();

var sorts = <?=CJSON::encode($js_sorts)?>;

function selectTask(taskID){
    $('li.task.selected').each(function(){
        if($(this).attr('id') != 'task'+taskID){
            $(this).removeClass('selected').find('.comments, .col-history li.more').hide();
        }
    });
    $('#task'+taskID).addClass('selected').find('.col-actions').show();
}

function addReply(commentID, taskID, author){
    $('#form-add-comment-task'+taskID)
        .find('input[name="taskID"]')
            .after('<div class="reply">'+
                '<input type="hidden" name="parentID" value="'+commentID+'">'+
                'Вы пишете ответ на комментарий #'+commentID+' от <b>'+author+'</b> '+
                '<a title="Не хочу писать ответ, буду писать новый комментарий"'+
                ' href="#" onclick="cancleReply('+taskID+');return false;">'+
                '<img src="/images/icons/close.png" alt="Не хочу писать ответ, буду писать новый комментарий"'+
                ' class="icon"></a>'+
                '</div>');
}
function cancleReply(taskID){
    $('#form-add-comment-task'+taskID)
        .find('div.reply').remove();
}

$(function(){
    var commentpatt = /comments-(\d)+/;
    var res = commentpatt.exec(location.hash);
    if(res && res[1] > 0){
        $('#commentstask'+res[1]).show();
        location.hash = res[0];
    }
    $('#tasklist  li.testing').css('opacity', 0.4);
    <?if($_TID > 0){?>selectTask(<?=$_TID?>);<?}?>
});

<?if(TaskUser::isManager()){?>
    function savePosition(){
        var pool = [];
        $('input[name="id"]').each(function(){
            pool.push($(this).val());
        });
        $.getJSON('<?=$this->createUrl('tools/savetaskposition',array('backurl'=>$_SERVER['REQUEST_URI']))?>', {'pool':pool,'sorts':sorts}, function(data){
            if(data.type == '<?=AjaxResult::TYPE_ERROR?>'){
                $().toastmessage('showErrorToast', data.message);
            }else{
                $().toastmessage('showSuccessToast', data.message);
            }
        });
    }
    $(function(){
        if($('#tasklist').length > 0){
            $('#tasklist').sortable({
                axis: 'y',
                cursor: 'row-resize',
                update: function(e, u){ savePosition(); }
            });
        }
    });
<?}?>
</script>
